package com.lihaozhe.inventoryservice.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClient;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 库存服务控制器
 * 演示库存服务如何通过负载均衡调用商品服务
 *
 * @author 李昊哲
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/inventory")
public class InventoryController {
  private final RestClient loadBalancedRestClient;
  private final LoadBalancerClient loadBalancerClient;
  private final Logger logger = LoggerFactory.getLogger(InventoryController.class);
  @Value("${server.port}")
  private String serverPort;

  public InventoryController(RestClient loadBalancedRestClient, LoadBalancerClient loadBalancerClient) {
    this.loadBalancedRestClient = loadBalancedRestClient;
    this.loadBalancerClient = loadBalancerClient;
  }

  /**
   * 检查商品库存 - 通过负载均衡调用商品服务
   * GET /api/inventory/check/{productId}
   */
  @GetMapping("/check/{productId}")
  public Map<String, Object> checkInventory(@PathVariable("productId") Long productId) {
    ServiceInstance instance = loadBalancerClient.choose("product-service");
    // 使用服务名进行调用，LoadBalancer会自动处理负载均衡
    String url = instance.getUri() + "/api/products/" + productId;

    try {
      // 定义泛型类型：Map<String, User>
      ParameterizedTypeReference<Map<String, Object>> typeRef = new ParameterizedTypeReference<Map<String, Object>>() {
      };
      Map<String, Object> response = loadBalancedRestClient.get()
          .uri(url)
          .retrieve()
          .body(typeRef);

      if (response != null && response.get("product") != null) {
        Map<String, Object> productMap = (Map<String, Object>) response.get("product");
        Map<String, Object> instanceInfo = (Map<String, Object>) response.get("instanceInfo");

        return Map.of(
            "productId", productId,
            "productName", productMap.get("name"),
            "stock", productMap.get("stock"),
            "price", productMap.get("price"),
            "checkedBy", "inventory-service:" + serverPort,
            "productServiceInstance", instanceInfo.get("instanceId"),
            "timestamp", System.currentTimeMillis()
        );
      }

      return Map.of(
          "productId", productId,
          "error", "商品不存在",
          "checkedBy", "inventory-service:" + serverPort
      );

    } catch (Exception e) {
      return Map.of(
          "productId", productId,
          "error", "检查库存失败: " + e.getMessage(),
          "checkedBy", "inventory-service:" + serverPort
      );
    }
  }

  /**
   * 批量检查库存
   * POST /api/inventory/batch-check
   */
  @PostMapping("/batch-check")
  public Map<String, Object> batchCheckInventory(@RequestBody Map<String, List<Long>> request) {
    List<Long> productIds = request.get("productIds");
    Map<String, Object> results = new HashMap<>();

    for (Long productId : productIds) {
      Map<String, Object> checkResult = checkInventory(productId);
      results.put("product_" + productId, checkResult);
    }

    return Map.of(
        "totalChecked", productIds.size(),
        "results", results,
        "checkedBy", "inventory-service:" + serverPort
    );
  }

  @GetMapping("/health")
  public Map<String, Object> health() {
    return Map.of(
        "status", "UP",
        "service", "inventory-service",
        "port", serverPort,
        "timestamp", System.currentTimeMillis()
    );
  }
}
